package comment

import (
	"fmt"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	_const "github.com/flipped-aurora/gin-vue-admin/server/global/const"
	"github.com/flipped-aurora/gin-vue-admin/server/model/comment/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/comment/response"
	sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"

	"gorm.io/gorm"

	"github.com/flipped-aurora/gin-vue-admin/server/model/comment"
	commentModel "github.com/flipped-aurora/gin-vue-admin/server/model/comment"
	contentModel "github.com/flipped-aurora/gin-vue-admin/server/model/content"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	serviceUtil "github.com/flipped-aurora/gin-vue-admin/server/utils/service"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"go.uber.org/zap"
)

type CommentCService struct {
}

var CommentCServiceApp = new(CommentCService)

// GetCommentList 评论区获取评论列表接口
func (c *CommentCService) GetCommentList(ctx *gin.Context, request request.QueryCommentCRequest) (response.QueryCommentCResponse, error) {
	uri := "GetCommentList"
	var logID = utils.GetLogID(ctx)
	// 1. 根据条件查询，获取评论数量；
	var total int64
	var db = global.GVA_DB.Model(&commentModel.SysComment{})
	var where string
	// 1.1、一级评论列表仅查询未删除的评论
	if serviceUtil.GetCommentLevelType(request.ParentCommentID) == serviceUtil.CommentLevelType1st {
		where = fmt.Sprintf("content_id = ? AND parent_comment_id = ? AND status = %d", _const.CommentStatusDefault)
	} else {
		where = "content_id = ? AND parent_comment_id = ?"
	}
	var errCount = db.Where(where, request.ContentID, request.ParentCommentID).Count(&total).Error
	if errCount != nil {
		global.GVA_LOG.Error("获取评论列表数量失败!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("content_id", request.ContentID),
			zap.Int64("parent_comment_id", request.ParentCommentID),
			zap.Error(errCount))
		return response.QueryCommentCResponse{}, fmt.Errorf("获取评论列表数量失败: %w", errCount)
	}

	// 处理排序方式和排序字段
	var order = _const.OrderAscStr
	switch request.Order {
	case _const.OrderAsc:
		order = _const.OrderAscStr
	case _const.OrderDesc:
		order = _const.OrderDescStr
	default:
		order = _const.OrderAscStr
	}

	var orderBy = _const.DefaultSortField
	if _, ok := _const.SupportSortFields[request.OrderBy]; ok {
		orderBy = request.OrderBy
	}
	var orderStr = fmt.Sprintf(" %s %s", orderBy, order)

	var commentList = make([]commentModel.SysComment, 0, request.PageInfo.PageSize)

	// 分页查询获取评论
	var errQuery = db.Scopes(request.PageInfo.Paginate()).Model(&commentModel.SysComment{}).Where(where,
		request.ContentID, request.ParentCommentID).Order(orderStr).Find(&commentList).Error
	if errQuery != nil {
		global.GVA_LOG.Error("获取评论列表失败!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("content_id", request.ContentID),
			zap.Int64("parent_comment_id", request.ParentCommentID),
			zap.String("order", orderStr),
			zap.Error(errQuery))
		return response.QueryCommentCResponse{}, fmt.Errorf("获取评论列表失败: %w", errQuery)
	}

	// 获取每一条评论的发布者信息 和 子评论数量
	var commentVoList = make([]response.CommentCVO, 0, len(commentList))
	for _, comment := range commentList {
		// 获取发布者信息
		if comment.PublisherID <= 0 {
			continue
		}
		var user sysModel.SysUser
		var errUser = global.GVA_DB.Model(&user).Where("id = ?", comment.PublisherID).First(&user).Error
		if errUser != nil {
			global.GVA_LOG.Warn("获取评论发布者信息失败!",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Uint("comment_id", comment.ID),
				zap.Int64("user_id", comment.PublisherID),
				zap.Error(errUser))
			continue
		}

		// 一级评论还需要获取子评论数量
		var childCount int64
		if serviceUtil.GetCommentLevelType(request.ParentCommentID) == serviceUtil.CommentLevelType1st {
			var errChildCount = global.GVA_DB.Model(&commentModel.SysComment{}).Where("content_id = ? AND parent_comment_id = ?",
				request.ContentID, comment.ID).Count(&childCount).Error
			if errChildCount != nil {
				global.GVA_LOG.Warn("获取子评论数量失败!",
					zap.String("uri", uri),
					zap.String("log_id", logID),
					zap.Int64("content_id", request.ContentID),
					zap.Uint("parent_comment_id", comment.ID),
					zap.Error(errChildCount))
			}
		}

		commentVO := response.CommentCVO{
			CommentID:       comment.ID,
			AnswerCommentID: comment.AnswerCommentID,
			ParentCommentID: comment.ParentCommentID,
			PublisherID:     user.ID,
			PublisherName:   user.NickName,
			PublisherImage:  user.HeaderImg,
			CommentText:     comment.CommentText,
			CreateTime:      comment.CreatedAt.Unix(),
			Likes:           comment.Likes,
			Dislikes:        comment.Dislikes,
			Marks:           comment.Marks,
			Shares:          comment.Shares,
			ChildComments:   childCount,
		}

		commentVoList = append(commentVoList, commentVO)
	}
	global.GVA_LOG.Info("获取评论列表成功!",
		zap.String("uri", uri),
		zap.String("log_id", logID),
		zap.Int64("content_id", request.ContentID),
		zap.Int64("parent_comment_id", request.ParentCommentID),
		zap.String("order", orderStr),
		zap.Int64("total", total))

	return response.QueryCommentCResponse{
		Total:    total,
		Comments: commentVoList,
	}, nil
}

// DeleteComment 删除自己发的评论及其全部子孙（软删除 status = 2）
func (c *CommentCService) DeleteComment(ctx *gin.Context, req request.DeleteCCommentId) error {
	uri := "DeleteComment"
	var logID = utils.GetLogID(ctx)

	// 1. 根据comment_id查询评论
	var comment commentModel.SysComment
	err := global.GVA_DB.Model(&commentModel.SysComment{}).
		Where("id = ?", req.CommentId).
		Take(&comment).Error
	if err != nil {
		global.GVA_LOG.Warn("查询评论失败",
			zap.String("log_id", logID),
			zap.String("uri", uri),
			zap.Int64("comment_id", req.CommentId),
			zap.Error(err))
		return errors.Wrap(err, "查询评论失败")
	}

	// 2. 根据评论的content_id查询文章
	var content contentModel.Content
	err = global.GVA_DB.Model(&contentModel.Content{}).
		Where("id = ?", comment.ContentID).
		Take(&content).Error
	if err != nil {
		global.GVA_LOG.Warn("查询评论所属内容失败",
			zap.String("log_id", logID),
			zap.String("uri", uri),
			zap.Int64("content_id", comment.ContentID),
			zap.Error(err))
		return errors.Wrap(err, "查询评论所属内容失败")
	}

	if comment.Status != int(_const.CommentStatusDefault) {
		global.GVA_LOG.Warn("评论已被删除或禁用, 不能删除!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("comment_id", req.CommentId),
			zap.Int("comment_status", comment.Status))
		return errors.New("评论已被删除或禁用, 不能删除!")
	}

	// 3. 验证权限：评论发布者或文章发布者可以删除评论
	if req.UserId != int64(comment.PublisherID) && req.UserId != int64(content.PublisherID) {
		global.GVA_LOG.Warn("无权限删除评论",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("user_id", req.UserId),
			zap.Uint("comment_publisher_id", uint(comment.PublisherID)),
			zap.Uint("content_publisher_id", content.PublisherID))
		return errors.New("评论删除失败, 只有文章发布者/评论发布者才能删除该评论")
	}

	// 4. 使用事务同时删除评论和更新内容评论数
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var affectedRows int64

		// 4.1 根据评论层级执行软删除操作
		if serviceUtil.GetCommentLevelType(comment.ParentCommentID) == serviceUtil.CommentLevelType1st {
			// 一级评论：删除所有子评论
			result := tx.Model(&commentModel.SysComment{}).
				Where("parent_comment_id = ? and status = ?", req.CommentId, _const.CommentStatusDefault).
				Update("status", _const.CommentStatusDeleted)
			if result.Error != nil {
				global.GVA_LOG.Warn("删除一级评论的子评论失败",
					zap.String("uri", uri),
					zap.String("log_id", logID),
					zap.Int64("comment_id", req.CommentId),
					zap.Int64("affected_rows", result.RowsAffected),
					zap.Error(result.Error))
				return errors.Wrap(result.Error, "删除子评论失败")
			}
			affectedRows += result.RowsAffected
		}
		// 一级/二级评论删除自身
		result := tx.Model(&commentModel.SysComment{}).
			Where("id = ? and status = ?", req.CommentId, _const.CommentStatusDefault).
			Update("status", _const.CommentStatusDeleted)
		if result.Error != nil {
			global.GVA_LOG.Warn("删除评论失败",
				zap.String("log_id", logID),
				zap.String("uri", uri),
				zap.Int64("comment_id", req.CommentId),
				zap.Error(result.Error))
			return errors.Wrap(result.Error, "删除评论失败")
		}
		affectedRows += result.RowsAffected

		// 4.2 更新内容评论数
		if affectedRows > 0 {
			errUpdate := tx.Model(&contentModel.ContentStats{}).
				Where("content_id = ?", comment.ContentID).
				Update("comments_count", gorm.Expr("comments_count - ?", affectedRows)).Error
			if errUpdate != nil {
				global.GVA_LOG.Error("更新内容评论数失败!",
					zap.String("uri", uri),
					zap.String("log_id", logID),
					zap.Int64("content_id", comment.ContentID),
					zap.Int64("affected_rows", affectedRows),
					zap.Error(errUpdate))
				return errUpdate
			}
			global.GVA_LOG.Debug("更新内容评论数成功",
				zap.String("log_id", logID),
				zap.String("uri", uri),
				zap.Int64("content_id", comment.ContentID),
				zap.Int64("decreased_count", affectedRows))
		}

		global.GVA_LOG.Info("评论删除成功",
			zap.String("log_id", logID),
			zap.String("uri", uri),
			zap.Int64("user_id", req.UserId),
			zap.Int64("comment_id", req.CommentId),
			zap.Int64("affected_rows", affectedRows))
		return nil
	})
}

// ClickCount 统计点赞,点踩,收藏,分享评论的次数，并记录用户操作
func (c *CommentCService) ClickCount(ctx *gin.Context, req request.ClickCount) (operate string, err error) {
	uri := "ClickCount"
	var logID = utils.GetLogID(ctx)
	// 1. 确定操作类型和对应的列名
	column := ""
	operate = ""
	actionType := global.ActionType(0)
	switch req.OpType {
	case _const.Likes:
		column = "likes"
		operate = "点赞"
		actionType = global.Like // 对应comment_action表中的1-like
	case _const.Dislikes:
		column = "dislikes"
		operate = "点踩"
		actionType = global.Dislike // 对应comment_action表中的2-dislike
	case _const.Marks:
		column = "marks"
		operate = "收藏"
		actionType = global.Mark // 对应comment_action表中的3-mark
	case _const.Shares:
		column = "shares"
		operate = "分享"
		actionType = global.Share // 对应comment_action表中的4-share
	case _const.Clicks:
		column = "click"
		operate = "点击"
		actionType = global.Click // 对应comment_action表中的6-click
	default:
		global.GVA_LOG.Warn("无效的操作类型",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("op_type", req.OpType))
		return operate, errors.New("无效的操作类型")
	}

	// 2. 获取当前用户ID
	userID := utils.GetUserID(ctx)
	if userID == 0 {
		global.GVA_LOG.Warn("用户未登录，无法记录操作",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("comment_id", req.CommentId),
			zap.Int64("op_type", req.OpType))
		return operate, nil
	}

	// 3. 开启事务，同时更新评论统计和记录用户操作
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 3.1 查询原始评论数据
		var origin int64
		if err := tx.Model(&commentModel.SysComment{}).
			Where("id = ?", req.CommentId).
			Select(column).
			Take(&origin).Error; err != nil {
			global.GVA_LOG.Error("查询评论原始统计数据失败",
				zap.String("uri", uri),
				zap.Int64("comment_id", req.CommentId),
				zap.String("column", column),
				zap.Error(err))
			return errors.Wrap(err, "查询评论统计数据失败")
		}
		// 3.2 查询用户操作记录，判断是否重复操作
		var existingAction = comment.CommentAction{}
		tx.Model(&comment.CommentAction{}).Where("user_id = ? and comment_id = ? and action_type = ?", userID, req.CommentId, int64(actionType)).
			First(&existingAction).Select("id")
		var existed = existingAction.ID > 0

		var newCount = origin
		// 3.3 处理重复操作 和 初次操作的计数变化
		if existed {
			switch actionType {
			case global.Like, global.Dislike, global.Mark:
				// 重复操作，计数 - 1
				newCount = origin - 1
			case global.Click, global.Share:
				// 点击操作，计数 + 1
				newCount = origin + 1
			}
		} else { // 初次操作，计数 + 1
			newCount = origin + 1
		}

		// 3.4 修改评论统计数据
		if err := tx.Model(&commentModel.SysComment{}).
			Where("id = ?", req.CommentId).
			Update(column, newCount).Error; err != nil {
			global.GVA_LOG.Error("更新评论统计数据失败",
				zap.String("uri", uri),
				zap.Int64("comment_id", req.CommentId),
				zap.String("column", column),
				zap.Int64("new_count", newCount),
				zap.Error(err))
			return errors.Wrap(err, "更新评论统计数据失败")
		}

		// 3.5 修改用户操作（如果用户已登录）

		if existed { // 重复操作——点赞/点踩/收藏 删除操作记录
			switch actionType {
			case global.Like, global.Dislike, global.Mark:
				if err := tx.Delete(&comment.CommentAction{}, "id = ?", existingAction.ID).Error; err != nil {
					global.GVA_LOG.Warn("删除用户评论操作记录失败",
						zap.String("uri", uri),
						zap.Uint("user_id", userID),
						zap.Int64("comment_id", req.CommentId),
						zap.Int64("action_type", int64(actionType)),
						zap.Error(err))
					// 删除操作失败不应影响主流程
				}

			}

		} else { // 初次操作——新增记录
			commentAction := comment.CommentAction{
				UserID:     userID,
				CommentID:  req.CommentId,
				ActionType: int64(actionType),
			}

			if err := tx.Create(&commentAction).Error; err != nil {
				global.GVA_LOG.Warn("记录用户评论操作失败",
					zap.String("uri", uri),
					zap.Uint("user_id", userID),
					zap.Int64("comment_id", req.CommentId),
					zap.Int64("action_type", int64(actionType)),
					zap.Error(err))
				// 记录操作失败不应影响主流程
			}
		}

		return nil
	})

	if err != nil {
		global.GVA_LOG.Error("处理评论互动失败",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("comment_id", req.CommentId),
			zap.Error(err))
		return operate, errors.Wrap(err, operate+"失败")
	}

	global.GVA_LOG.Info("处理评论互动成功",
		zap.String("uri", uri),
		zap.String("log_id", logID),
		zap.Int64("comment_id", req.CommentId),
		zap.String("operate", operate))
	return operate, nil
}

// AddComment 发布评论
func (c *CommentCService) AddComment(ctx *gin.Context, request request.AddCommentRequest) error {
	uri := "AddComment"
	var logID = utils.GetLogID(ctx)

	var content contentModel.Content
	global.GVA_DB.Model(&content).Where("id = ?", request.ContentID).First(&content)
	if content.ID == 0 {
		global.GVA_LOG.Warn("评论关联的内容不存在!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("content_id", request.ContentID))
		return errors.New("评论关联的内容不存在")
	}
	if content.Status != global.ContentStatusNormal {
		global.GVA_LOG.Warn("评论关联的内容已被删除或禁用!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("content_id", request.ContentID))
		return errors.New("评论关联的内容已被删除或禁用")
	}

	var parentComment commentModel.SysComment
	if request.ParentCommentID > 0 {
		if err := global.GVA_DB.Where("id = ? and status = ?", request.ParentCommentID, _const.CommentStatusDefault).First(&parentComment).Error; err != nil {
			global.GVA_LOG.Warn("查询父评论失败! 或父评论已被删除或禁用!",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("parent_comment_id", request.ParentCommentID),
				zap.Int("parent_comment_status", parentComment.Status),
				zap.Error(err))
			return errors.New("查询父评论失败! 或父评论已被删除或禁用!")
		}
	}

	var answerComment commentModel.SysComment
	if request.AnswerCommentID > 0 {
		if err := global.GVA_DB.Where("id = ? and status = ?", request.AnswerCommentID, _const.CommentStatusDefault).First(&answerComment).Error; err != nil {
			global.GVA_LOG.Warn("查询回复评论失败! 或回复评论已被删除或禁用!",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("answer_comment_id", request.AnswerCommentID),
				zap.Error(err))
			return errors.New("查询回复评论失败! 或回复评论已被删除或禁用!")
		}
	}

	// todo 权限校验
	var comment = commentModel.SysComment{
		ContentID:       request.ContentID,
		ParentCommentID: request.ParentCommentID,
		AnswerCommentID: request.AnswerCommentID,
		PublisherID:     request.PublisherID,
		CommentText:     request.CommentText,
	}

	// 使用事务同时创建评论和更新内容评论数
	err := global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		errCreate := tx.Create(&comment).Error
		if errCreate != nil {
			global.GVA_LOG.Error("发布评论失败!",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Error(errCreate))
			return errCreate
		}

		// 增加内容评论数
		errUpdate := tx.Model(&contentModel.ContentStats{}).
			Where("content_id = ?", request.ContentID).
			Update("comments_count", gorm.Expr("comments_count + 1")).Error
		if errUpdate != nil {
			global.GVA_LOG.Error("更新内容评论数失败!",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("content_id", request.ContentID),
				zap.Error(errUpdate))
			return errUpdate
		}

		global.GVA_LOG.Info("发布评论成功!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Uint("comment_id", comment.ID))
		return nil
	})

	return err
}

// UpdateComment 修改评论
func (c *CommentCService) UpdateComment(ctx *gin.Context, request request.UpdateCommentRequest) error {
	uri := "UpdateComment"
	var logID = utils.GetLogID(ctx)

	// todo 权限校验

	var commentModel = commentModel.SysComment{}
	var errQuery = global.GVA_DB.Model(&commentModel).Where("id = ?", request.ID).First(&commentModel).Error
	if errQuery != nil {
		global.GVA_LOG.Warn("查询评论失败!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("id", request.ID),
			zap.Error(errQuery))
		return errQuery
	}
	// 校验评论的状态
	if commentModel.Status != 0 {
		global.GVA_LOG.Warn("无效的评论修改操作!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("id", request.ID),
			zap.Int("status", commentModel.Status))

		return fmt.Errorf("invalid update comment operation! id=%d, status=%d", request.ID, commentModel.Status)
	}

	// 校验当前登陆用户和评论发布者是否一致
	var currentUserID = int64(utils.GetUserID(ctx))
	if currentUserID != commentModel.PublisherID {
		global.GVA_LOG.Warn("无效的评论修改操作!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("id", request.ID),
			zap.Int64("user_id", currentUserID),
			zap.Int64("publiser", commentModel.PublisherID))
		return errors.New("invalid update comment operation")
	}

	// 修改评论内容，并同步至db
	commentModel.CommentText = request.CommentText
	var updateErr = global.GVA_DB.Model(&commentModel).
		Where("id = ?", commentModel.ID).
		Update("comment_text", commentModel.CommentText).Error
	if updateErr != nil {
		global.GVA_LOG.Warn("修改评论失败!",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("id", request.ID),
			zap.String("comment_text", request.CommentText),
			zap.Error(updateErr))
		return updateErr
	}

	// 更新评论内容，以及评论更新时间
	global.GVA_LOG.Info("修改评论成功!",
		zap.String("uri", uri),
		zap.String("log_id", logID),
		zap.Int64("id", request.ID),
		zap.String("update_time", commentModel.UpdatedAt.String()))
	return nil
}

// GetCommentUserAction 查询用户评论操作记录
func (c *CommentCService) GetCommentUserAction(ctx *gin.Context, req request.CommentUserActionRequest) (response.CommentUserActionResponse, error) {
	uri := "GetCommentUserAction"
	var logID = utils.GetLogID(ctx)

	// 1. 确定要查询的用户ID
	queryUserID := req.UserID
	if queryUserID <= 0 {
		// 如果未传递用户ID或用户ID小于等于0，查询当前登录用户
		queryUserID = int64(utils.GetUserID(ctx))
		if queryUserID <= 0 {
			global.GVA_LOG.Warn("用户未登录，无法查询评论操作记录",
				zap.String("uri", uri),
				zap.String("log_id", logID))
			return response.CommentUserActionResponse{}, errors.New("用户未登录")
		}
	}

	// 2. 根据操作类型确定查询逻辑
	var commentIDs []int64
	var commentActions []comment.CommentAction
	var total int64
	var err error

	if req.ActionType == global.ActionType(-1) {
		// 操作类型为-1：查询用户发布的评论
		// todo: 先暂时不通过status过滤评论，由前端进行控制
		// 先统计总条数
		// err = global.GVA_DB.Model(&commentModel.SysComment{}).
		// 	Where("publisher_id = ? AND status = ?", queryUserID, _const.CommentStatusDefault).
		// 	Count(&total).Error
		err = global.GVA_DB.Model(&commentModel.SysComment{}).
			Where("publisher_id = ?", queryUserID).
			Count(&total).Error
		if err != nil {
			global.GVA_LOG.Error("统计用户发布评论数量失败",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("user_id", queryUserID),
				zap.Error(err))
			return response.CommentUserActionResponse{}, errors.Wrap(err, "统计评论数量失败")
		}

		// 查询评论ID

		// err = global.GVA_DB.Model(&commentModel.SysComment{}).
		// 	Select("id").
		// 	Where("publisher_id = ? AND status = ?", queryUserID, _const.CommentStatusDefault).
		// 	Scopes(req.Paginate()).
		// 	Order("created_at DESC").
		// 	Pluck("id", &commentIDs).Error
		err = global.GVA_DB.Model(&commentModel.SysComment{}).
			Select("id").
			Where("publisher_id = ?", queryUserID).
			Scopes(req.Paginate()).
			Order("created_at DESC").
			Pluck("id", &commentIDs).Error
		if err != nil {
			global.GVA_LOG.Error("查询用户发布评论ID失败",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("user_id", queryUserID),
				zap.Error(err))
			return response.CommentUserActionResponse{}, errors.Wrap(err, "查询评论ID失败")
		}
	} else if req.ActionType == global.Like || req.ActionType == global.Mark {
		// 操作类型为1(点赞)或3(收藏)：查询用户的点赞或收藏评论
		// 先统计总条数
		err = global.GVA_DB.Model(&comment.CommentAction{}).
			Where("user_id = ? AND action_type = ?", queryUserID, req.ActionType).
			Count(&total).Error
		if err != nil {
			global.GVA_LOG.Error("统计用户评论操作数量失败",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("user_id", queryUserID),
				zap.Int64("action_type", int64(req.ActionType)),
				zap.Error(err))
			return response.CommentUserActionResponse{}, errors.Wrap(err, "统计操作数量失败")
		}

		// 查询评论ID和操作时间
		err = global.GVA_DB.Model(&comment.CommentAction{}).
			Where("user_id = ? AND action_type = ?", queryUserID, req.ActionType).
			Scopes(req.Paginate()).
			Order("created_at DESC").
			Find(&commentActions).Error
		if err != nil {
			global.GVA_LOG.Error("查询用户评论操作记录失败",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("user_id", queryUserID),
				zap.Int64("action_type", int64(req.ActionType)),
				zap.Error(err))
			return response.CommentUserActionResponse{}, errors.Wrap(err, "查询操作记录失败")
		}

		// 提取评论ID
		for _, action := range commentActions {
			commentIDs = append(commentIDs, action.CommentID)
		}
	} else {
		global.GVA_LOG.Warn("无效的操作类型",
			zap.String("uri", uri),
			zap.String("log_id", logID),
			zap.Int64("action_type", int64(req.ActionType)))
		return response.CommentUserActionResponse{}, errors.New("无效的操作类型")
	}

	// 3. 如果没有找到评论，直接返回空结果
	if len(commentIDs) == 0 {
		return response.CommentUserActionResponse{
			Total:    0,
			Comments: []response.CommentUserActionVO{},
		}, nil
	}

	// 4. 查询评论详情
	var comments []commentModel.SysComment
	for _, commentID := range commentIDs {
		var comment commentModel.SysComment
		err = global.GVA_DB.Where("id = ?", commentID).First(&comment).Error
		if err != nil {
			global.GVA_LOG.Error("查询评论详情失败",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("comment_id", commentID),
				zap.Error(err))
			// 继续处理下一条，不中断整个查询
			continue
		}
		comments = append(comments, comment)
	}

	// 如果没有查询到任何评论，直接返回空结果
	if len(comments) == 0 {
		return response.CommentUserActionResponse{
			Total:    0,
			Comments: []response.CommentUserActionVO{},
		}, nil
	}

	// 5. 提取内容ID列表，查询内容信息
	var contentIDs []int64
	for _, comment := range comments {
		contentIDs = append(contentIDs, comment.ContentID)
	}

	contentMap := make(map[int64]contentModel.Content)
	for _, contentID := range contentIDs {
		// 检查是否已经查询过该内容
		if _, exists := contentMap[contentID]; exists {
			continue
		}

		var content contentModel.Content
		err = global.GVA_DB.Where("id = ?", contentID).
			Select("id", "title", "type").
			First(&content).Error
		if err != nil {
			global.GVA_LOG.Error("查询内容信息失败",
				zap.String("uri", uri),
				zap.String("log_id", logID),
				zap.Int64("content_id", contentID),
				zap.Error(err))
			// 继续处理下一条，不中断整个查询
			continue
		}
		contentMap[content.ID] = content
	}

	// 6. 转换为CommentUserActionVO对象
	var resultComments []response.CommentUserActionVO
	for _, comment := range comments {
		content, contentExists := contentMap[comment.ContentID]
		var contentTitle string
		var contentType int
		if contentExists {
			contentTitle = content.Title
			contentType = int(content.Type)
		}

		// 查询回复的评论信息（如果有）
		var answerCommentText string
		var answerCommentPublisherName string
		var answerCommentPublisherID uint
		var answerCommentStatus int
		if comment.AnswerCommentID > 0 {
			var answerComment commentModel.SysComment
			global.GVA_DB.Where("id = ?", comment.AnswerCommentID).First(&answerComment)
			if answerComment.ID > 0 {
				answerCommentText = answerComment.CommentText
				// 查询回复评论发布者信息
				var answerPublisher systemModel.SysUser
				global.GVA_DB.Where("id = ?", answerComment.PublisherID).
					Select("id", "nick_name").
					First(&answerPublisher)
				if answerPublisher.ID > 0 {
					answerCommentPublisherName = answerPublisher.NickName
					answerCommentPublisherID = answerPublisher.ID
					answerCommentStatus = answerComment.Status
				}
			}
		}

		// 查询评论发布者信息
		var publisherName string
		var publisher systemModel.SysUser
		global.GVA_DB.Where("id = ?", comment.PublisherID).
			Select("id", "nick_name").
			First(&publisher)
		if publisher.ID > 0 {
			publisherName = publisher.NickName
		}

		// 确定操作时间
		actionTime := comment.CreatedAt.Unix()
		// 如果是点赞或收藏操作，需要从comment_action表中获取操作时间
		if req.ActionType == global.Like || req.ActionType == global.Mark {
			for _, action := range commentActions {
				if action.CommentID == int64(comment.ID) {
					actionTime = action.CreatedAt.Unix()
					break
				}
			}
		}

		resultComments = append(resultComments, response.CommentUserActionVO{
			ContentID:    uint(comment.ContentID),
			ContentType:  contentType,
			ContentTitle: contentTitle,

			AnswerCommentID:            uint(comment.AnswerCommentID),
			AnswerCommentText:          answerCommentText,
			AnswerCommentPublisherName: answerCommentPublisherName,
			AnswerCommentPublisherID:   answerCommentPublisherID,
			AnswerCommentStatus:        answerCommentStatus,

			CommentID:     comment.ID,
			CommentText:   comment.CommentText,
			PublisherID:   uint(comment.PublisherID),
			PublisherName: publisherName,
			PublishTime:   comment.CreatedAt.Unix(),
			CommentStatus: comment.Status,

			ActionTime: actionTime,
		})
	}

	global.GVA_LOG.Info("查询用户评论操作记录成功",
		zap.String("uri", uri),
		zap.String("log_id", logID),
		zap.Int64("user_id", queryUserID),
		zap.Int64("action_type", int64(req.ActionType)),
		zap.Int64("total", total))

	return response.CommentUserActionResponse{
		Total:    total,
		Comments: resultComments,
	}, nil
}
